import hashlib
import os
import random
import re
import base64
import datetime
import time

from PIL import Image
from io import BytesIO
import shutil


def md5Encoding(youstr):
    m = hashlib.md5()
    m.update(youstr.encode())
    encodingstr = m.hexdigest()
    print(encodingstr)
    return encodingstr
md5Encoding("12345678")
def validate_phone(number):
    pattern = r'^1[3456789]\d{9}$'  # 这里的正则表达式只能验证中国大陆地区的手机号码格式
    if re.match(pattern, number):
        return True
    else:
        return False


def image_to_base64(image,content_type):
    if content_type is None:
        content_type = image.content_type
    img_format = content_type.split("/")[1]
    img = Image.open(image)
    buffered = BytesIO()
    img.save(buffered, format=img_format)
    return "data:" + content_type + ";base64," + base64.b64encode(buffered.getvalue()).decode("utf-8")


def delete_files(folder_path):
    files = os.listdir(folder_path)
    for file in files:
        file_path = os.path.join(folder_path, file)
        if os.path.isfile(file_path):
            os.remove(file_path)


def delete_folder(path):
    try:
        shutil.rmtree(path)
    except OSError as e:
        print(f"删除文件夹 {path} 失败: {e}")

def get_upload_file_size(fobj):
    if fobj.content_length:
        return fobj.content_length
    try:
        pos = fobj.tell()
        fobj.seek(0, 2)  # seek to end
        size = fobj.tell()
        fobj.seek(pos)  # back to original position
        return size
    except (AttributeError, IOError):
        pass
    # in-memory file object that doesn't support seeking or tell
    return 0  # assume small enough

def order_uuid():
    """
    """
    order_id = str(datetime.datetime.fromtimestamp(time.time())).replace("-", "").replace(" ", "").replace(":","").replace(".", "") + str(random.randint(100, 999))
    return order_id

def calculate_characters(amount, rates, preferentials):
    # 定义每个档次的金额和对应的字符数
    # rates = {
    #     20: 30000,
    #     50: 100000,
    #     100: 220000,
    #     200: 500000,
    #     300: 800000,
    #     500: 1500000
    # }
    # # 促销活动折扣价
    # if amount == 9.9:
    #     return 30000
    for preferential in sorted(preferentials.keys(), reverse=True):
        if amount == preferential:
            return preferentials[preferential]
    # 找到最接近但不大于输入金额的档次
    for price in sorted(rates.keys(), reverse=True):
        if amount >= price:
            # 计算比例
            proportion = amount / price
            # 计算字符数
            characters = rates[price] * proportion
            return int(characters)  # 转换为整数并返回

    # 如果输入金额小于20元，则按最低档次计算
    return 0

def get_day_start_end(date_str):
    # 解析日期字符串
    date = datetime.datetime.strptime(date_str, '%Y-%m-%d')

    # 当天的开始时间
    start_time = datetime.datetime.combine(date, datetime.datetime.min.time())

    # 当天的结束时间
    end_time = datetime.datetime.combine(date, datetime.datetime.max.time())

    return start_time, end_time
